package timer

import (
	"time"

	"go-share/logging"
)

type TimerTask struct{}

func NewTimerTask() *TimerTask {
	return &TimerTask{}
}

// 执行定时任务,每天hour点钟执行一次
func (this *TimerTask) ExecEverydayByHour(hour int, f func()) {

	// 定时时间
	now := time.Now()
	specialTime := time.Date(now.Year(), now.Month(), now.Day(), hour, 0, 0, 0, time.Local)
	var duration time.Duration
	if now.After(specialTime) {
		duration = specialTime.AddDate(0, 0, 1).Sub(now)
	} else {
		duration = specialTime.Sub(now)
	}
	logging.Notice("[TimerTask] After %v Starting!", duration)

	time.AfterFunc(duration,
		func() {
			logging.Notice("[TimerTask] Begin! %v", time.Now().String())

			// 每天定时执行一次
			var ticker *time.Ticker
			for {
				go f()

				// 阻塞
				ticker = time.NewTicker(24 * time.Hour)
				select {
				case <-ticker.C:
				}
			}
		},
	)
}

// 执行定时任务，每minute分钟执行一次
func (this *TimerTask) ExecEveryMinute(minute int64, f func()) {

	duration := time.Duration(minute) * time.Minute
	time.AfterFunc(duration,
		func() {
			logging.Notice("[TimerTask] Begin! %v", time.Now().String())

			// 每天定时执行一次
			var ticker *time.Ticker
			for {
				go f()

				// 阻塞
				ticker = time.NewTicker(duration)
				select {
				case <-ticker.C:
				}
			}
		},
	)
}
